<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Admin\Data\Common;
use Admin\Data\Config;
use Admin\Service\Common\PhoneMessage;
use Admin\Service\Common\ShopMessage;
use Doctrine\ORM\EntityManager;
use Laminas\Config\Factory;
use Laminas\Filter\StaticFilter;
use Laminas\Math\Rand;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\I18n\Translator;
use PHPQRCode\QRcode;
use User\Entity\User;

class IndexController extends AbstractActionController
{
    private $translator;
    private $entityManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager
    )
    {
        $this->translator   = $translator;
        $this->entityManager= $entityManager;
    }

    /**
     * 首页
     * @return array|\Laminas\Http\Response|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $this->getEventManager()->trigger('shop.index.post', $this);

        //当前的页面，用来区分首页在layout中使用
        $this->layout()->setVariable('shopCurrentPage', 'index');

        $indexPartial = $this->shopPlugin()->shopPartial('index');

        return ['indexPartial' => $indexPartial];
    }

    /**
     * 切换货币
     */
    public function changeCurrencyAction()
    {
        $currencyCode = StaticFilter::execute($this->request->getQuery('code'), 'StringToUpper');
        $currencyInfo = Common::configValue($currencyCode, 'currency');
        if($currencyInfo && $currencyInfo['state'] == 1) {
            $this->shopPlugin()->setDbshopSessionData('currencyCode', $currencyInfo['code']);
        }
        return $this->shopPlugin()->toReferer();
    }

    /**
     * 手机验证码发送
     * @return mixed
     */
    public function sendPhoneCaptchaAction()
    {
        $areaCode   = $this->params()->fromPost('areaCode', '');
        $phoneNumber= $this->params()->fromPost('phoneNumber', '');
        $checkUserPhone = $this->params()->fromPost('checkUserPhone', '');

        if (empty($phoneNumber)) return $this->response->setContent($this->translator->translate('请填写手机号码!'));
        if (!Common::checkPhoneNumber($phoneNumber, $areaCode)) return $this->response->setContent($this->translator->translate('手机号码不正确!'));

        if ($checkUserPhone == 'checkNotExist') {//判断手机号码不存在
            $userInfo = $this->entityManager->getRepository(User::class)->findOneBy(['userPhone' => $phoneNumber, 'areaCode' => $areaCode]);
            if ($userInfo == null) return $this->response->setContent($this->translator->translate('该手机号码不存在!'));
        }
        if ($checkUserPhone == 'checkExist') {//判断手机号码存在
            $userInfo = $this->entityManager->getRepository(User::class)->findOneBy(['userPhone' => $phoneNumber, 'areaCode' => $areaCode]);
            if ($userInfo) return $this->response->setContent($this->translator->translate('该手机号码已经存在!'));
        }

        $expiredTime = (int) $this->shopPlugin()->getDbshopSessionData('expiredTime');
        if ($expiredTime > 0 && $expiredTime > time()) return $this->response->setContent($this->translator->translate('获取时间未到，不可重复获取验证码!'));

        $phoneCaptcha = Rand::getString(4, '1234567890');

        $this->shopPlugin()->setDbshopSessionData('phoneCaptcha', $phoneCaptcha);
        $this->shopPlugin()->setDbshopSessionData('phoneNumber', $phoneNumber);
        $this->shopPlugin()->setDbshopSessionData('expiredTime', time() + Config::PHONE_CAPTCHA_EXPIRED_SECOND);

        $message = '';//当消息为空时，则发送成功
        try {
            PhoneMessage::sendSms(['phoneAreaCode' => $areaCode, 'phone' => $phoneNumber, 'contentArray' => ['phoneCaptcha' => $phoneCaptcha], 'templateCode' => 'captcha']);
        } catch (\Exception $e) {
            $message = $this->translator->translate('验证码发送错误!');
        }

        return $this->response->setContent($message);
    }

    /**
     * 邮箱验证码发送
     * @return mixed
     * @throws \PHPMailer\PHPMailer\Exception
     */
    public function sendEmailCaptchaAction()
    {
        if(!$this->shopPlugin()->checkUserLoginStatus()) return $this->response->setContent($this->translator->translate('非法请求，会员未登录'));

        $expiredTime = (int) $this->shopPlugin()->getDbshopSessionData('emailExpiredTime');
        if ($expiredTime > 0 && $expiredTime > time()) return $this->response->setContent($this->translator->translate('获取时间未到，不可重复获取验证码!'));

        $emailCaptcha = Rand::getString(6, '1234567890');

        $this->shopPlugin()->setDbshopSessionData('emailCaptcha', $emailCaptcha);
        $this->shopPlugin()->setDbshopSessionData('emailExpiredTime', time() + Config::EMAIL_CAPTCHA_EXPIRED_SECOND);

        $userInfo = $this->entityManager->getRepository(User::class)->findOneBy(['userId' => $this->shopPlugin()->getUserLoginData('user_id')]);
        if (empty($userInfo->getUserEmail())) return $this->response->setContent($this->translator->translate('邮箱为空，不能发送邮箱验证码'));

        $sendStatus = ShopMessage::sendMail([
            'mail'      => $userInfo->getUserEmail(),
            'subject'   => $this->translator->translate('邮箱验证码'),
            'body'      => $userInfo->getUserName() . '<br>' . $this->translator->translate('您好，您的邮箱验证码为') . $emailCaptcha
        ]);

        if(!$sendStatus) return $this->response->setContent($this->translator->translate('邮件发送错误'));

        return $this->response->setContent(sprintf($this->translator->translate('已经成功向您的邮箱 %s 发送一封邮箱验证码的邮件，请登录您的邮箱进行查看'), $userInfo->getUserEmail()));
    }

    /**
     * 通过url调用二维码
     * @return mixed
     */
    public function shopQrCodeFileAction()
    {
        if(!$this->shopPlugin()->validatorQueryCsrf()) return $this->response->setContent('非法访问!');
        return $this->response->setContent(QRcode::png(urldecode($this->params()->fromQuery('data')), false, 0, 8, 1));
    }

    /**
     * updateKey输出
     * @return mixed
     */
    public function outputUpdateKeyAction()
    {
        $updateKey      = '';
        $actionName     = StaticFilter::execute($this->params()->fromQuery('actionName'), 'HtmlEntities');
        $updateKeyArray = Factory::fromFile(Config::PACKAGE_UPDATE_KEY_FILE);
        if (isset($updateKeyArray[$actionName]) && !empty($updateKeyArray[$actionName])) $updateKey = $updateKeyArray[$actionName];

        return $this->response->setContent($updateKey);
    }
}